package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/regions")
public class RegionController {

    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ServletContext servletContext;

    /**
     * 查询所有的旅游地区给前端
     * 请求方式:Get
     *
     * @return
     */
    @GetMapping
    public List<Region> listAll(Integer state) {
        return regionService.selectAll(state);
    }

    /**
     * 以流的方式响应给浏览器,因此该方法的返回类型为void
     * 查询该地区推荐攻略(设置热门状态,不分页)
     * 查询该地区全部攻略
     * 创建freemarker的配置对象,配置最新版本
     * 设置模板所在目录 -- (注入上下文对象,获取文档位置)
     * 设置编码格式
     * 获取模板
     * 数据封装在map中
     * 模板和数据合成 (.process), 以流的形式响应
     */
    @GetMapping(value = "/{regionId}/strategies", produces = "text/html;charset=utf-8")
    public void queryStrategiesByRegionId(StrategyQueryObject qo, HttpServletResponse response) throws Exception {

        qo.setState(null);
        qo.setPageSize(2);
        PageInfo all = strategyService.query(qo);

        qo.setState(Strategy.STATE_HOT);//设置推荐的状态
        qo.setPageSize(0);//不分页
        PageInfo hot = strategyService.query(qo);


        Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
        configuration.setDirectoryForTemplateLoading(new File(servletContext.getRealPath("template")));
        configuration.setDefaultEncoding("UTF-8");
        Template template = configuration.getTemplate("strategyTemplate.ftl");

        HashMap<String, Object> map = new HashMap<>();
        map.put("hot", hot.getList());
        map.put("all", all.getList());

        response.setContentType("text/html;charset=utf-8");
        template.process(map, response.getWriter());

    }

    /**
     * 获取某个地区的攻略信息
     * 与上面的方法路径相同,区别是返回json数据
     * 用途:用于APP分页滚动
     * @param qo
     * @return
     */
    @GetMapping(value = "/{regionId}/strategies", produces = "application/json;charset=utf-8")
    public PageInfo queryStrategiesByRegionId(StrategyQueryObject qo) {

        //需要和上面的方法设置一样的参数
        qo.setPageSize(2);
        return strategyService.selectForList(qo);
    }
}
